import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '../router'
import tool from './tool'

const otherReq = ['downLoad', 'downLoad2', 'downloadTemplate']

let address = process.env.NODE_ENV == 'development' ? process.env.VUE_APP_URL : process.env.VUE_APP_BASE_API_PARENT;


// create an axios instance
const service = axios.create({
  baseURL: address, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: -1 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let token = tool.getCookie('X-Token');
    config.headers['X-TOKEN'] = token
    config.headers['client-url']=location.href
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    var url = response.request.responseURL
    var split = url.split('/')
    var laststr = split[split.length - 1]
    var lastUrl = laststr.split('?')[0]
    if (lastUrl === 'flow') {
      return response
    }
    if (otherReq.indexOf(lastUrl) !== -1) {
      return response
    }
    if (url.indexOf('/data-source/data/') !== -1) {
      return response.data
    }

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      if (res.code === 50101 || res.code === 50102) {
        // 获取登录页访问地址
        let ypt = process.env.NODE_ENV == 'development' ? process.env.VUE_APP_HOME_URL : process.env.VUE_APP_HOME_URL_PROD;
        // 如果当前路由不是登录页，跳转到登录页
        if(window.location.href.indexOf(ypt) === -1){
          window.localStorage.clear();
          tool.clearAllCookie()
          localStorage.stop = true;
          window.location.href = ypt
        }
        return 
      } else if (res.code === 50107) { // 修改密码
        router.push({
          name: 'uploadPassword', params: { token: res.data.token }
        })
      } else if (res.code === 99999) { // 未授权
        router.push({ path: '/empower/empower' })
      }

      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
      // return res
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
